package com.coocaa.ops.api.v1.content.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.coocaa.ops.api.common.constant.ApiTabType;
import com.coocaa.ops.api.common.util.PluginUtil;
import com.coocaa.ops.api.v1.content.constant.ContainerTypeConstants;
import com.coocaa.ops.api.v1.content.model.internal.PanelContentInfo;
import com.coocaa.ops.api.v1.content.model.internal.TabContentInfo;
import com.coocaa.ops.api.v1.content.model.internal.TabStreamContentInfo;
import com.coocaa.ops.api.v1.content.model.output.TabContent;
import com.coocaa.ops.api.v1.content.model.output.TabExtra;
import com.coocaa.ops.api.v1.content.model.output.normal.Container;
import com.coocaa.ops.api.v1.content.model.output.normal.ContainerForRecStreamBlock;
import com.coocaa.ops.api.v1.content.model.output.normal.block.*;
import com.coocaa.ops.api.v1.content.model.output.normal.expander.Expander;
import com.coocaa.ops.api.v1.content.model.output.normal.panel.Panel;
import com.coocaa.ops.api.v1.content.model.output.normal.panel.RecStreamPanel;
import com.coocaa.ops.api.v1.content.model.output.stream.StreamContent;
import com.coocaa.ops.common.core.biz.cornericon.entity.GlobalCornerIconEntity;
import com.coocaa.ops.common.core.biz.layout.constant.LayoutTypeConstants;
import com.coocaa.ops.common.core.biz.layout.entity.LayoutInfoEntity;
import com.coocaa.ops.common.core.biz.panel.constant.BlockRlsPictureTypeConstants;
import com.coocaa.ops.common.core.biz.panel.constant.DynamicSwitchConstants;
import com.coocaa.ops.common.core.biz.panel.constant.PanelTypeConstants;
import com.coocaa.ops.common.core.biz.panel.entity.BlockContentConfigInfo;
import com.coocaa.ops.common.core.biz.panel.entity.BlockExtendPosterInfoEntity;
import com.coocaa.ops.common.core.biz.panel.entity.BlockPictureRlsEntity;
import com.coocaa.ops.common.core.biz.plugin.entity.PluginInfoEntity;
import com.coocaa.ops.common.core.biz.tab.entity.TabInfoEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author tangminghong
 * @date 2020-06-28
 */
public class TabContentResultUtil {

    public static TabContent buildNormalTabContentResult(TabContentInfo tabContent, TabInfoEntity tab) {
        if (tabContent == null || tab == null) {
            return new TabContent();
        }
        TabContent result = new TabContent();
        result.setTotal(tabContent.getTotalCount());
        result.setType(ApiTabType.convertFromCommonTabType(tab.getTabType()));
        result.setExtra(new TabExtra(tab.getBackgroundPoster(), tab.getBackgroundColor()));

        Container container = new Container();
        container.setType(ContainerTypeConstants.EXPANDER);

        Expander expanderExtra = new Expander();
        expanderExtra.setOrientation(1);
        expanderExtra.setSpace(40);
        expanderExtra.setTitle(getExpanderTitle(tab));

        container.setExtra(expanderExtra);
        container.setContents(tabContent.getContent());

        result.setTab(container);

        return result;
    }

    private static Title getExpanderTitle(TabInfoEntity tab) {
        if (Objects.equals(1, tab.getShowTitle())) {
            return new Title(tab.getTabTitle(), null);
        }
        return new Title(null, null);
    }

    public static TabContent buildStreamTabContentResult(TabStreamContentInfo streamContent, TabInfoEntity tab) {
        if (streamContent == null || streamContent.getStreamContent() == null || tab == null) {
            return new TabContent();
        }
        List<StreamContent> streamList = streamContent.getStreamContent();
        TabContent result = new TabContent();
        result.setTotal(streamContent.getTotalCount());
        result.setType(ApiTabType.convertFromCommonTabType(tab.getTabType()));
        result.setTab(streamList);

        return result;
    }

    /**
     * 构建板块container
     *
     * @param panelContent
     * @return
     */
    public static Container buildPanelContainer(PanelContentInfo panelContent) {
        if (panelContent == null) {
            return new Container();
        }

        Container panel = new Container();

        handlePanelTypeAndPlugin(panel, panelContent);


        panel.setExtra(getPanelExtra(panelContent));

        panel.setContents(buildBlockContainer(panelContent.getPanelType(), panelContent.getBlockContentList()));
        panel.setId(panelContent.getId());

        handleLayout(panel, panelContent.getLayoutInfo());

        return panel;

    }


    private static List buildBlockContainer(String panelType, List<BlockContentConfigInfo> blockContentList) {
        if (CollectionUtils.isEmpty(blockContentList)) {
            return Collections.emptyList();
        }

        List<Container> blockList = new ArrayList<>(blockContentList.size());
        for (BlockContentConfigInfo blockInfo : blockContentList) {
            Container block;

            //推荐流板块底下的block为固定位置的，需要使用特殊的container并加入seq
            if (PanelTypeConstants.isRecStream(panelType)) {
                block = new ContainerForRecStreamBlock();
                ((ContainerForRecStreamBlock) block).setSeq(blockInfo.getBlockSeq());
            } else {
                block = new Container();
            }

            block.setId(blockInfo.getId());

            handleBlockTypeAndPlugin(block, blockInfo);

            Block blockExtra = new Block();
            blockExtra.setParams(blockInfo.getParams());


            blockExtra.setBlockTitle(handleBlockTitle(blockInfo));

            BlockContent blockContent = new BlockContent();
            blockContent.setAction(blockInfo.getOnclick());
            blockContent.setImgs(handleBlockImgs(blockInfo));
            blockContent.setTitle(blockInfo.getTitle());

            blockExtra.setBlockContent(blockContent);

            //TODO 客户端修改后去除
            if (PanelTypeConstants.isRecStream(panelType)) {
                blockExtra.setBlockSeq(blockInfo.getBlockSeq());
            }


            block.setExtra(blockExtra);

            blockList.add(block);

        }

        return blockList;
    }

    private static BlockTitle handleBlockTitle(BlockContentConfigInfo blockInfo) {
        Title title = new Title();
        title.setText(Objects.equals(1, blockInfo.getShowTitle()) ? blockInfo.getTitle() : null);
        Title subTitle = new Title();
        subTitle.setText(Objects.equals(1, blockInfo.getShowSubTitle()) ? blockInfo.getSubTitle() : null);
        return new BlockTitle(title, subTitle);
    }

    private static Imgs handleBlockImgs(BlockContentConfigInfo blockInfo) {
        Imgs imgs = new Imgs();

        Poster poster = new Poster();
        poster.setImages(Collections.singletonList(blockInfo.getPictureUrl()));
        imgs.setPoster(poster);

        List<CornerIcon> cornerIcons = new ArrayList<>(4);
        List<GlobalCornerIconEntity> cornerIconList = blockInfo.getCornerList();
        if (CollectionUtils.isNotEmpty(cornerIconList)) {
            for (GlobalCornerIconEntity cornerIcon : cornerIconList) {
                cornerIcons.add(new CornerIcon(cornerIcon.getPosition(), cornerIcon.getImgUrl()));
            }
        }
        imgs.setCornerIcons(cornerIcons);
        Dynamic dynamic = getDynamic(blockInfo);
        poster.setDynamic(dynamic);
        return imgs;
    }


    private static void handleLayout(Container panelContainer, LayoutInfoEntity layout) {
        if (layout == null || StringUtils.isBlank(layout.getLayoutJson())) {
            return;
        }
        String layoutJsonStr = layout.getLayoutJson();
        try {
            JSONObject layoutJson = JSONObject.parseObject(layoutJsonStr);
            String type = layoutJson.getString("type");
            if (LayoutTypeConstants.EXPANDER.equals(type)) {
                handleLayoutExpander(panelContainer, layoutJson);
            } else if (LayoutTypeConstants.LENGTHWISE.equals(type)) {
                handleLayoutLengthwise(panelContainer, layoutJson.getJSONArray("contents"));
            } else {
                handleLayoutPanel(panelContainer, layoutJson.getJSONArray("contents"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void handleLayoutPanel(Container panelContainer, JSONArray layoutContents) {
        List contents = panelContainer.getContents();
        if (CollectionUtils.isEmpty(contents)) {
            return;
        }
        int i = 0;
        Integer lastX = 0, lastWidth = 0;
        for (Object content : contents) {
            Container blockContainer = (Container) content;
            if (i < layoutContents.size()) {
                JSONObject layoutItem = (JSONObject) layoutContents.get(i);
                blockContainer.setX(lastX = layoutItem.getInteger("x"));
                blockContainer.setY(layoutItem.getInteger("y"));
                blockContainer.setWidth(lastWidth = layoutItem.getInteger("width"));
                blockContainer.setHeight(layoutItem.getInteger("height"));
                i++;
            }

        }
        if (lastX + lastWidth > 1760) {
            panelContainer.setType(ContainerTypeConstants.SCROLL_PANEL);
            panelContainer.setParents(ContainerTypeConstants.PANEL);
        } else {
            panelContainer.setType(ContainerTypeConstants.PANEL);
        }
    }

    private static void handleLayoutExpander(Container panelContainer, JSONObject layoutJson) {
        List contents = panelContainer.getContents();
        JSONObject extra = layoutJson.getJSONObject("extra");
        Integer space = extra.getInteger("space");

        JSONArray layoutContents = layoutJson.getJSONArray("contents");
        JSONObject layoutContent = (JSONObject) layoutContents.get(0);
        Integer x = layoutContent.getInteger("x");
        Integer y = layoutContent.getInteger("y");
        Integer width = layoutContent.getInteger("width");
        Integer height = layoutContent.getInteger("height");

        for (Object content : contents) {
            Container blockContainer = (Container) content;

            blockContainer.setX(x);
            blockContainer.setY(y);
            blockContainer.setWidth(width);
            blockContainer.setHeight(height);

            x += (width + space);

        }

        panelContainer.setType(ContainerTypeConstants.SCROLL_PANEL);
        panelContainer.setParents(ContainerTypeConstants.PANEL);
    }

    private static void handleLayoutLengthwise(Container panelContainer, JSONArray layoutContents) {
        List contents = panelContainer.getContents();
        if (CollectionUtils.isEmpty(contents)) {
            return;
        }
        int i = 0, columns = layoutContents.size(), ySpace = 40, height = 0, y = 0;
        for (Object content : contents) {
            Container blockContainer = (Container) content;
            if (i < layoutContents.size()) {
                JSONObject layoutItem = (JSONObject) layoutContents.get(i);
                blockContainer.setX(layoutItem.getInteger("x"));
                blockContainer.setY(layoutItem.getInteger("y") + y);
                blockContainer.setWidth(layoutItem.getInteger("width"));
                blockContainer.setHeight(height = layoutItem.getInteger("height"));
                i++;
                if (i >= columns) {
                    i = 0;
                    y = y + height + ySpace;
                }
            }

        }
        panelContainer.setType(ContainerTypeConstants.PANEL);

    }

    private static void handlePanelTypeAndPlugin(Container panelContainer, PanelContentInfo panel) {
        if (PanelTypeConstants.isRecStream(panel.getPanelType())) {
            panelContainer.setParents(ContainerTypeConstants.PANEL);
            panelContainer.setType(ContainerTypeConstants.REC_STREAM);
            return;
        }
        PluginInfoEntity pluginEntity = panel.getPluginInfo();
        if (panel.getPluginSelfId() == null || pluginEntity == null) {
            panelContainer.setType(ContainerTypeConstants.PANEL);
            return;
        }
        panelContainer.setType(ContainerTypeConstants.PLUGIN);
        panelContainer.setParents(ContainerTypeConstants.PANEL);
        panelContainer.setPluginInfo(PluginUtil.convertPluginInfo(pluginEntity));

    }

    private static void handleBlockTypeAndPlugin(Container blockContainer, BlockContentConfigInfo block) {
        PluginInfoEntity pluginEntity = block.getPluginInfo();
        if (block.getPluginSelfId() == null || pluginEntity == null) {
            blockContainer.setType(ContainerTypeConstants.BLOCK);
            return;
        }
        blockContainer.setType(ContainerTypeConstants.PLUGIN);
        blockContainer.setParents(ContainerTypeConstants.BLOCK);
        blockContainer.setPluginInfo(PluginUtil.convertPluginInfo(pluginEntity));
    }


    private static Panel getPanelExtra(PanelContentInfo panelContent) {
        String panelType = panelContent.getPanelType();
        Panel panelExtra;
        if (PanelTypeConstants.isRecStream(panelType)) {
            panelExtra = new RecStreamPanel();
            ((RecStreamPanel) panelExtra).setRecStreamId(panelContent.getRecStreamId());
        } else {
            panelExtra = new Panel();
        }
        panelExtra.setPanelVersion(Objects.toString(panelContent.getCurrentVersion()));
        panelExtra.setPanelName(panelContent.getPanelName());

        if (Objects.equals(1, panelContent.getShowTitle())) {
            panelExtra.setPanelTitle(new Title(panelContent.getPanelTitle(), 32));
        } else {
            panelExtra.setPanelTitle(new Title(null, null));
        }
        return panelExtra;
    }


    private static Dynamic getDynamic(BlockContentConfigInfo blockContentConfigInfo) {
        BlockExtendPosterInfoEntity blockExtendPosterInfoEntity = blockContentConfigInfo.getExtendPosterInfo();
        List<BlockPictureRlsEntity> blockPictureRlsList = blockContentConfigInfo.getBlockPictureRlsList();
        if (null != blockExtendPosterInfoEntity && DynamicSwitchConstants.isOpenDynamic(blockExtendPosterInfoEntity.getDynamicPosterSwitch()) && CollectionUtils.isNotEmpty(blockPictureRlsList)) {
            Dynamic dynamic = new Dynamic();
            dynamic.setDynamicPosterAlign(blockExtendPosterInfoEntity.getDynamicPosterAlign());
            dynamic.setFrontPosterUrl(getPictureUrlByType(blockPictureRlsList, BlockRlsPictureTypeConstants.BLOCK_FRONT_PICTURE));
            dynamic.setBackgroundPosterUrl(getPictureUrlByType(blockPictureRlsList, BlockRlsPictureTypeConstants.BLOCK_BACKGROUND_PICTURE));
        }
        return null;
    }

    public static String getPictureUrlByType(List<BlockPictureRlsEntity> blockPictureRlsList, Integer pictureType) {
        String pictureUrl = blockPictureRlsList.stream()
                .filter((BlockPictureRlsEntity item) -> Objects.equals(item.getPictureType(), pictureType))
                .findFirst().map(BlockPictureRlsEntity::getPictureUrl).orElse("");
        return pictureUrl;
    }

    public static void main(String[] args) {
        List<BlockPictureRlsEntity> blockPictureRlsList = InstanceUtil.newArrayList();
        for (int i=0; i< 7; i++){
            BlockPictureRlsEntity blockPictureRlsEntity = new BlockPictureRlsEntity();
            blockPictureRlsEntity.setPictureId(i);
            blockPictureRlsEntity.setPictureType(i);
            blockPictureRlsEntity.setPictureUrl(i+"wwww");
            blockPictureRlsList.add(blockPictureRlsEntity);
        }
        String res = getPictureUrlByType(blockPictureRlsList, 6);
        System.out.println(res);
    }
}

